define([ "jquery", "underscore", "alertify", "imgareaselect" ], function($, _, alertify, imgsel) {

	var _tmpl = [
		'<div class="modal fade" id="_avatar_upload" tabindex="-1" role="dialog"  aria-hidden="true">',
		'  <div class="modal-dialog">',
		'    <div class="modal-content">',
		'      <div class="modal-header">',
		// ' <button type="button" class="close"
		// data-dismiss="modal"
		// aria-hidden="true">&times;</button>',
		'        <h4 class="modal-title" id="_avatar_upload_title">Modal title</h4>',
		'      </div>',
		'      <div class="modal-body">',
		' 加载中...',
		'      </div>',
		'      <div class="modal-footer">',
		'        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>',
		'        <button type="button" id="btn-upload" class="btn btn-primary btn-upload" >上传图片</button>',
		'        <button type="button" class="btn btn-primary btn-confirm" style="display:none;">保存图片</button>',
		'        <button type="button" class="btn btn-default btn-reupload" style="display:none;">重新上传</button>',
		'        <span id="span-container"></span>',
		'      </div>',
		'    </div>',
		'  </div>',
		'</div>' ].join("");

	var A_DEFAULT = {
		type: "user",
		uptoken_url: (window.CTX || '') + '/api/fs/image/uptoken?pathPrefix=pubservices/'
	};

	var imgSelect;
	var preview = function(img, selection) {
		var scaleX = 100 / selection.width;
		var scaleY = 100 / selection.height;
		$('#avatar-preview img').css({
			width : Math.round(scaleX * $("#avatar-photo").width()),
			height : Math.round(scaleY * $("#avatar-photo").height()),
			marginLeft : -Math.round(scaleX * selection.x1),
			marginTop : -Math.round(scaleY * selection.y1)
		});
		var scaleX = 50 / selection.width;
		var scaleY = 50 / selection.height;
		$('#avatar-preview-s img').css({
			width : Math.round(scaleX * $("#avatar-photo").width()),
			height : Math.round(scaleY * $("#avatar-photo").height()),
			marginLeft : -Math.round(scaleX * selection.x1),
			marginTop : -Math.round(scaleY * selection.y1)
		});
	};
	function _checkDom() {
		console.log("_checkDom");
		if (!$("#_avatar_upload")[0]) {
			$(document.body).append(_tmpl);
			initEvent();
		}
		initUploader();
	};
	function initEvent() {
		$("#_avatar_upload").on("click", ".btn-confirm", function() {
			form = $.extend(imgSelect.getSelection(), {
				originalImage : window.originalImage,
				height : $('#avatar-photo').height(),
				width : $('#avatar-photo').width(),
				ownerId : _ownerId,
				type : serviceType
			});
			var originalImage = window.originalImage;

			var imgHeight = $('#avatar-photo').height();
			var imgWidth = $('#avatar-photo').width();

			var realWidth = $('#realImg').width();
			var realHeight = $('#realImg').height();

			var scale = realWidth / imgWidth;

			selectWidth = Math.round(imgSelect.getSelection().width * scale);
			selectHeight = Math.round(imgSelect.getSelection().height * scale);

			var x = Math.round(imgSelect.getSelection().x1 * scale);

			var y = Math.round(imgSelect.getSelection().y1 * scale);

			var imageMogrParam = originalImage.indexOf('?') >= 0 ? '&' : '?';
			imageMogrParam += "imageMogr2/crop/!" + selectWidth + "x" + selectHeight + "a" + x + "a" + y;

			originalImage += imageMogrParam;

			var saveBut = $("#_avatar_upload").find("button.btn-confirm");
			if (selectWidth > 0 && selectHeight > 0) {
				saveBut.attr("disabled", true);
				console.log(form);
				$.ajax({
					url : _avatarSaveUrl,
					type : 'POST',
					async : false,
					data : {
						"avatarUrl" : originalImage,
						"ownerId" : _ownerId
					},
					success : function(resp) {
						imgSelect.remove();
						imgSelect.update();
						$("#_avatar_upload").modal("hide");
						if (_callback) {
							_callback(resp);							
						}
						if (resp) {
							alertify.success("修改成功");
						} else {
							alertify.error("修改失败，请联系系统管理员解决");
						}
					},
					complete : function() {
						saveBut.attr("disabled", false);
					}
				});
			} else {
				alertify.error("请裁剪图片");
			}
		});

		$('#_avatar_upload').on("click", ".btn-reupload", function() {
			initUploader();
			setTimeout(function() {
				$('#btn-upload').click();
			}, 500);
		});

		$('#_avatar_upload').on('hide.bs.modal', function(e) {
			if (imgSelect) {
				imgSelect.remove();
				imgSelect.update();
			}
		});
	};
	
	var _qiniuUploader;
	function initUploader() {
		// 七牛图片上传
		if (_qiniuUploader) {
			_qiniuUploader.destroy();
			$('#btn-upload').unbind();
			var _native = o || mOxie
			if (_native) {
				_native.removeAllEvents(document.getElementById('btn-upload'));
			}
		}
		_qiniuUploader = null;
		console.log("vUpTokenUrl:" + vUpTokenUrl);
		$.ajax({
			url : vUpTokenUrl,
			type : 'GET',
			async : false,
			success : function(dat) {
				var token = dat.uptoken;
				var path = dat.path;
				var _domain = dat.domain;
				
				//console.log(token);
				//console.log(path);
				_qiniuUploader = Qiniu.uploader({
					runtimes : 'html5,html4',
					browse_button : 'btn-upload', // 上传选择的点选按钮，**必需**
					container: 'span-container',
					// uptoken_url: vUpTokenUrl,
					uptoken : token,
					domain : _domain,
					max_file_size : '5mb',
					max_retries : 3,
					auto_start : true,
					multi_selection: false,//单文件
			    	filters : [ {title : "图片上传", extensions : "png,jpg,jpeg,gif,bmp"} ], //文件过滤
					init : {
						'FileUploaded' : function(up, file, info) {
							console.log("info:===" + info);
							var domain = up.getOption('domain');
							var res = $.parseJSON(info);
							var sourceLink = domain + res.key;
							sourceLink += "?v=" + new Date().getTime();
							$("input[name='imageUrl']").val(sourceLink);
							window.originalImage = sourceLink;
							//console.log("sourceLink:" + sourceLink);
							//console.log("originalImage:" + originalImage);

							$("#avatar-body").html(_.template($("#avatar-cutting-tmpl").html(), { originalImage : sourceLink }));
							$('#avatar-photo').on("load", function() {
								var coord1 = {}, coord2 = {};
								
								var w = $('#avatar-photo').width(), 
									h = $('#avatar-photo').height();
								var r = Math.min(w, h) * 0.8;
								var x = (w - r) / 2, 
									y = (h - r) / 2;
								coord1.x = x,
								coord2.x = x + r,
								coord1.y = y,
								coord2.y = y + r;
								
								if (imgSelect) {
									imgSelect.remove();
								}

								imgSelect = $('#avatar-photo').imgAreaSelect({
									x1 : coord1.x,
									y1 : coord1.y,
									x2 : coord2.x,
									y2 : coord2.y,
									instance : true,
									aspectRatio : _aspectRatio + ":1",
									handles : true,
									onSelectChange : preview
								});
								preview(null, imgSelect.getSelection());
								$("#_avatar_upload").find(".btn-upload").hide();
								$("#_avatar_upload").find(".btn-reupload").show();
								$("#_avatar_upload").find(".btn-confirm").show();
								$("#_avatar_upload").find("button.btn-confirm").attr("disabled", false);
							});
						},
						'Error' : function(up, err, errTip) {
							if(err.message=="File extension error."){//格式不正确
			            		alertify.error("文件格式不正确(格式为：png,jpg,jpeg,gif,bmp)！");
				            }
				            if(err.message=="File size error."){//大小超过
				            	alertify.error("文件大小不能超过5M！");
				            }
						},
						'Key' : function(up, file) {
							console.log("Key:" + path);
							return path;
						}
					}
				});
			},
			error : function(e) {
				console.log("error:");
				console.log(e);
			}
		});
	};

	var _callback;
	var _ownerId;
	var _avatarSaveUrl;
	var _aspectRatio = 1;
	var serviceType;
	var vUpTokenUrl = null;
	var defaultIcon="blank_avatar.png";
	avatar = {
		change : function(opt, callback) {
			var _optTemplate = $.extend(true, {}, A_DEFAULT);
			opt = $.extend(true, _optTemplate, opt);
			serviceType = opt.type;
			vUpTokenUrl = opt.uptoken_url;
			defaultIcon=opt.type.defaultIcon;
			//
			_checkDom();
			//console.log("opt:");
			//console.log(opt);
			//console.log("vUpTokenUrl:"+vUpTokenUrl);
			$("#_avatar_upload_title").html(opt.type.title);
			$("#_avatar_upload").modal("show");
			var url = opt.type.url + (opt.ownerId ? "?ownerId=" + opt.ownerId : "");
			url+="&defaultIcon="+defaultIcon;
			
			_avatarSaveUrl = opt.type.saveUrl;
			_ownerId = opt.ownerId;
			console.log("load body url :" + url);
			$("#_avatar_upload").find(".modal-body").load(url, function() {
				$("#avatar-body").html(_.template($("#avatar-upload-tmpl").html()));
				$("#_avatar_upload").find(".btn-upload").show();
				$("#_avatar_upload").find(".btn-reupload").hide();
				$("#_avatar_upload").find(".btn-confirm").hide();
			});
			_callback = callback;
		}
	}
	return avatar;
});
